<?php
namespace common\steamauth;
use think\Request;
use common\libs\Curl;
/**
 * This class provides a simple interface for OpenID 1.1/2.0 authentication.
 * 
 * It requires PHP >= 5.1.2 with cURL or HTTP/HTTPS stream wrappers enabled.
 *
 * @version     v1.3.1 (2016-03-04)
 * @link        https://code.google.com/p/lightopenid/          Project URL
 * @link        https://github.com/iignatov/LightOpenID         GitHub Repo
 * @author      Mewp <mewp151 at gmail dot com>
 * @copyright   Copyright (c) 2013 Mewp
 * @license     http://opensource.org/licenses/mit-license.php  MIT License
 */
class LightOpenID
{
    const OPENID_URL = 'https://steamcommunity.com/openid/login';
	public $data = [];
	public $request;
	public $loginResult;
	
	public function __construct($trustRoot,$returnUrl){
		$this->returnUrl = $returnUrl;
		$this->trustRoot = $trustRoot;
		$this->request = Request::instance();
		$this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET;
	}
	public  function authUrl(){
		return $this->authUrl_v2();
	}
	
	public function getSteamId(){
		preg_match("#^https://steamcommunity.com/openid/id/([0-9]{17,25})#", $this->request->get('openid_claimed_id'), $matches);
		return is_numeric($matches[1]) ? $matches[1] : 0;
	}
	function __set($name, $value)
	{
		switch ($name) {
			case 'identity':
				if (strlen($value = trim((String) $value))) {
					if (preg_match('#^xri:/*#i', $value, $m)) {
						$value = substr($value, strlen($m[0]));
					} elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
						$value = "http://$value";
					}
					if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
						$value .= '/';
					}
				}
				$this->$name = $this->claimed_id = $value;
				break;
			case 'trustRoot':
			case 'realm':
				$this->trustRoot = trim($value);
				break;
			case 'returnUrl':
				$this->returnUrl = trim($value);
				break;
		}
	}
	
	function __get($name)
	{
		switch ($name) {
			case 'identity':
				# We return claimed_id instead of identity,
				# because the developer should see the claimed identifier,
				# i.e. what he set as identity, not the op-local identifier (which is what we verify)
				return $this->claimed_id;
			case 'trustRoot':
			case 'realm':
				return $this->trustRoot;
			case 'returnUrl':
				return $this->returnUrl;
			case 'mode':
				return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
		}
	}

	
	
    protected function authUrl_v2($immediate = false)
    {
        $params = array(
            'openid.ns'          => 'http://specs.openid.net/auth/2.0',
            'openid.mode'        => $immediate ? 'checkid_immediate' : 'checkid_setup',
            'openid.return_to'   => $this->returnUrl,
            'openid.realm'       => $this->trustRoot,
        	'openid.identity'   => 'http://specs.openid.net/auth/2.0/identifier_select',
        	'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
        );
        return self::OPENID_URL.'?'.http_build_query($params, '', '&');
    }
    /**
     * Checks the steam login
     *
     * @return bool
     */
    public function validate(){
    	if (!$this->requestIsValid()){
    		return false;
    	}
    	$params = $this->getParams();
   		$response = Curl::http_post( self::OPENID_URL, $params);
    	if(strpos($response, 'is_valid:true') === false){
    		return false;
    	} 
    	$result['is_valid'] = true;
    	$this->loginResult = $result;
    	return true;
    }
    private function requestIsValid()
    {
    	return $this->request->has('openid_assoc_handle')
    	&& $this->request->has('openid_signed')
    	&& $this->request->has('openid_sig');
    }
    
    /**
     * Get param list for openId validation
     *
     * @return array
     */
    public function getParams()
    {
    	$params = [
    	'openid.assoc_handle' => $this->request->get('openid_assoc_handle'),
    	'openid.signed'       => $this->request->get('openid_signed'),
    	'openid.sig'          => $this->request->get('openid_sig'),
    	'openid.ns'           => 'http://specs.openid.net/auth/2.0',
    	'openid.mode'         => 'check_authentication'
    			];
    
    	$signedParams = explode(',', $this->request->get('openid_signed'));
    
    	foreach ($signedParams as $item) {
    		$value = $this->request->get('openid_' . str_replace('.', '_', $item));
    		$params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($value) : $value;
    	}
    
    	return $params;
    }
}